<template>
  <div>
    <a-row :gutter="10">
      <a-col :md="8" :sm="24">
        <a-card :bordered="false">
          <a-tabs default-active-key="1" @change="changeTabPane">
            <a-tab-pane key="1" tab="目录">
              <div>
                <!--<a-input-search @search="onSearch" style="width:100%;margin-top: 10px" placeholder="请输入目录名称"/>-->
                <!-- 树-->
                <template v-if="departTree.length>0">
                  <!--组织机构-->
                  <a-tree
                    showLine
                    :load-data="onLoadData"
                    :selectedKeys="selectedKeys"
                    :checkStrictly="true"
                    @select="onSelect"
                    :dropdownStyle="{maxHeight:'200px',overflow:'auto'}"
                    :treeData="departTree"
                    :autoExpandParent="autoExpandParent"
                    :expandedKeys="iExpandedKeys"
                    @expand="onExpand"
                  />

                </template>
                <div style="margin-top: 24px;" v-else-if="departTree.length==0">
                  <h3><span>暂无有效目录信息</span></h3>
                </div>
                <div style="margin-top: 24px;" v-else><h3>暂无数据</h3></div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="设备">
              <DtgLeftTree :selectedKeys="selectedKeysDetachment" @selectNode="selectNode"></DtgLeftTree>
            </a-tab-pane>
          </a-tabs>

        </a-card>
      </a-col>
      <a-col :md="16" :sm="24">
        <a-card :bordered="false" style="margin: 0">
          <a-button :disabled="selectedRowKeys.length ? false : true " type="primary" icon="download" @click="handleExportXls" style="margin-bottom: 10px;">导出</a-button>
          <a-table
            rowKey="id"
            style="height: 400px; overflow: auto"
            :pagination="false"
            :columns="columns"
            :data-source="tableData"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          ></a-table>

          <div class="ant-alert ant-alert-info" style="margin: 16px 0;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i>
            <span>已选择文件</span>
            <a style="font-weight: 600">
              {{ selectedRowKeys.length }}
            </a>
            <span>项</span>
            <!--<a style="margin-left: 24px" @click="onClearSelected">清空</a>-->
          </div>

          <a-table
            rowKey="id"
            style="height: 400px; overflow: auto"
            :pagination="false"
            :columns="selColumns"
            :data-source="selData"
          >
            <span slot="action" slot-scope="text, record">
              <a @click="removeDoc(record.id)">移除</a>
            </span>
          </a-table>
        </a-card>
      </a-col>
    </a-row>


    <!-- 弹窗 -->
    <a-modal v-model="visible" title="请选择支队" :width="800" @ok="handleOk">
      <a-table
        rowKey="id"
        :pagination="false"
        :columns="columnsEx"
        :data-source="ExData"
        :row-selection="{ selectedRowKeys: selectedRowKeysEx, onChange: onSelectChangeEx, type: 'radio' }"
      ></a-table>
    </a-modal>

  </div>
</template>


<script>
  import { searchByKeywords} from '@/api/api'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import { getAction } from '@/api/manage'
  import DtgLeftTree from './modules/DtgLeftTree'
  import { fileDetailsInfoGetByPid,getBranchInfoList,unzipExportzip } from '@/api/digitization'

  const tHead = [
    {
      title: '文件名',
      dataIndex: 'fileTitle',
      align: "center",
    },
    {
      title: '大小(MB)',
      dataIndex: 'fileSize',
      align: "center",
      customRender: function (t, r, index) {
        let size = (parseInt(t) / 1024 / 1024).toFixed(2);
        return size < 0.1 ? '不足0.1MB' : size ;
      }
    },
    {
      title: '类型',
      dataIndex: 'fileTypes',
      align: "center",
    },
  ];

  export default {
    name: 'DtgExport',
    mixins: [JeecgListMixin],
    components: {
      DtgLeftTree
    },
    data() {
      return {
        departTree: [],
        selectedKeys: [],
        selectedKeysNode: {},
        iExpandedKeys: [],
        loading: false,
        autoExpandParent: true,
        columns: tHead,
        tableData: [],
        selectedRowKeys: [],
        visible: false,
        selectedRowKeysEx:[],
        columnsEx:[
          {
            title: '支队名',
            dataIndex: 'name',
            align: "center",
          },
          {
            title: '备注',
            dataIndex: 'memo',
            align: "center",
          },
        ],
        ExData:[],
        selectedKeysDetachment:[],
        currentTreeKey:'',
        selDocList:{},
        selColumns:[
          ...tHead,
          {
            title: '操作',
            dataIndex: 'action',
            align: "center",
            scopedSlots: {customRender: 'action'},
          }
        ],
        selData:[]

      }
    },
    created() {


    },
    methods: {
      changeTabPane(k){
        this.tableData = [];
        this.selectedKeys = [];
        this.selectedKeysDetachment = [];
      },
      selectNode(v){
        this.selectedKeysDetachment = v.selKeys;
        this.currentTreeKey = v.selKeys[0];

        this.getFileDetailsInfoGetByPid(v.selKeys);
      },
      handelExpanded(selKeys){
        this.onExpand(selKeys);
        this.onLoadData(this.selectedKeysNode)
      },
      onSelectChange(selectedRowKeys,rows) {
        this.selectedRowKeys = selectedRowKeys;
        if(rows.length){
          this.selDocList[this.currentTreeKey] = rows;
        }else{
          delete this.selDocList[this.currentTreeKey]
        }

        this.viewSelTable();
        // console.log(selectedRowKeys,rows)
        console.log(this.selDocList)
      },
      onSelectChangeEx(selectedRowKeys,rows) {
        this.selectedRowKeysEx = selectedRowKeys;
      },
      viewSelTable(){
        let tmp = [];
        for(let id in this.selDocList){
          tmp.push(...this.selDocList[id]);
        }
        this.selData = tmp;
      },
      removeDoc(id){
        let i = this.selectedRowKeys.findIndex(res => res == id);
        let _i = this.selData.findIndex(res => res.id == id);
        this.selectedRowKeys.splice(i,1);
        this.selData.splice(_i,1);

        for(let name in this.selDocList){
          let o = this.selDocList[name].findIndex(opt => opt.id == id);
          if(o > -1){
            this.selDocList[name].splice(o,1);

            if(!this.selDocList[name].length){
              delete this.selDocList[name]
            }
          }
        }
        console.log(this.selDocList);
      },
      loadData() {
        this.refresh();
      },
      loadTree() {
        let that = this
        that.departTree = []

        getAction("/base/fmTypeDetails/rootList","").then(res=>{
          if (res.success && res.result ) {
          for (let i = 0; i < res.result.records.length; i++) {
              let temp = res.result.records[i]
              temp['title'] = temp.typeName;
              temp['key'] = temp.id;

              if(temp.hasChild == '1'){
                temp['children'] = [{}];
              }
              that.departTree.push(temp)
            }
            that.loading = false
          }
        })
      },
      setThisExpandedKeys(node) {
        //只展开一级目录
        if (node.children && node.children.length > 0) {
          this.iExpandedKeys.push(node.key)
          //下方代码放开注释则默认展开所有节点
          /**
           for (let a = 0; a < node.children.length; a++) {
            this.setThisExpandedKeys(node.children[a])
          }
           */
        }
      },
      refresh() {
        this.loading = true
        this.loadTree()
      },
      onExpand(expandedKeys) {
        this.iExpandedKeys = expandedKeys
        this.autoExpandParent = false
      },
      onLoadData(treeNode) {
        return new Promise(resolve => {
          if (treeNode.dataRef.hasChild!='1') {
            resolve();
            return;
          }
          setTimeout(() => {
            getAction("/base/fmTypeDetails/childList?pid="+treeNode.eventKey).then(res=>{
              if (res.success && res.result ) {
                treeNode.dataRef.children = [];
                for (let i = 0; i < res.result.records.length; i++) {
                   let temp = res.result.records[i]
                   temp['title'] = temp.typeName;
                   temp['key'] = temp.id;

                   if(temp.hasChild == '1'){
                     temp['children'] = [];
                   }else{
                     temp['children'] = null;
                   }
                   treeNode.dataRef.children.push(temp);
                   resolve();
                 }
                }
            });
          }, 100);
        });
      },
      onSelect(selectedKeys, e) {
        this.selectedKeys = selectedKeys
        this.selectedKeysNode = e.node
        this.currentTreeKey = selectedKeys[0];

        this.getFileDetailsInfoGetByPid(selectedKeys);
      },
      getFileDetailsInfoGetByPid(selectedKeys){
        fileDetailsInfoGetByPid({pid:selectedKeys[0]}).then(res => {
          this.tableData = res.result;
        })
      },
      handleExportXls(){
        this.visible = true;

        getBranchInfoList().then(res => {
          this.ExData = res.result.records;
        })
      },
      handleOk(){
        this.visible = false;
        let tmp = [];
        this.selData.forEach(opt => {
          tmp.push(opt.id);
        })
        let params = 'fileIds=' + tmp.join(',') + '&' + 'branchId=' + this.selectedRowKeysEx.join(',');
        unzipExportzip(params).then(res => {
          this.$message.success(res.message)
          this.loadData();
          this.changeTabPane();
          this.selData = [];

          this.iExpandedKeys = [];
          this.autoExpandParent = true;
        })
      },
      onSearch(value) {
        let that = this
        if (value) {
          searchByKeywords({keyWord: value,myDeptSearch:'1'}).then((res) => {
            if (res.success) {
              that.departTree = []
              for (let i = 0; i < res.result.length; i++) {
                let temp = res.result[i]
                that.departTree.push(temp)
              }
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          that.loadTree()
        }

      },


    },
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>